<template>
  <div class="chat-container">
    <el-card class="chat-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">智能助手</span>
          <el-button type="danger" size="small" @click="clearChat" plain round>
            <el-icon><Delete /></el-icon>
            清空对话
          </el-button>
        </div>
      </template>
        
      <div class="chat-wrapper">
        <el-scrollbar height="800px">
        <div class="chat-messages" ref="messagesContainer">
          <div v-for="(message, index) in messages" :key="index" 
              :class="['message', message.role]">
            <div class="message-avatar">
              <el-avatar :icon="message.role === 'user' ? User : StarFilled" />
            </div>
            <div class="message-content">
              <div class="message-role">{{ message.role === 'user' ? '你' : 'AI助手' }}</div>
              <div class="message-text" v-html="message.content"></div>
            </div>
          </div>
          <div v-if="loading" class="message assistant">
            <div class="message-avatar">
              <el-avatar :icon="StarFilled" />
            </div>
            <div class="message-content">
              <div class="message-role">AI助手</div>
              <div class="message-text">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span class="loading-text">思考中...</span>
              </div>
            </div>
          </div>
        </div>
        </el-scrollbar>
      </div>
     
      <div class="chat-input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="2"
          :maxrows="4"
          placeholder="请输入您的问题..."
          resize="none"
          @keyup.enter.native="sendMessage"
          class="input-box"
        />
        <div class="input-actions">
          <el-button 
            type="primary" 
            @click="sendMessage"
            :disabled="!inputMessage.trim() || loading"
            class="send-button"
            round
          >
            发送 <el-icon class="icon-right"><Promotion /></el-icon>
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
// 导入Vue相关功能和图标
import { ref, onMounted, nextTick } from 'vue'
import { User, StarFilled, Loading, Delete, Promotion } from '@element-plus/icons-vue'
// 导入聊天API服务
import chatApi from '../../services/chat.js'

// 定义消息列表，初始包含一条欢迎消息
const messages = ref([
  {
    role: 'assistant',
    content: '您好！我是AI助手，有什么可以帮您的吗？'
  }
])

// 定义输入消息的响应式变量
const inputMessage = ref('')
// 定义加载状态的响应式变量
const loading = ref(false)
// 定义消息容器的DOM引用
const messagesContainer = ref(null)

// 滚动到底部的函数
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 提取最终回答的函数（过滤掉AI思考过程）
const extractFinalResponse = (rawResponse) => {
  // 方案1：如果回复有固定分隔符
  const separator = "最终回答：";
  const separatorIndex = rawResponse.lastIndexOf(separator);
  if (separatorIndex >= 0) {
    return rawResponse.substring(separatorIndex + separator.length).trim();
  }
  
  // 方案2：匹配最后一个段落
  const paragraphs = rawResponse.split('\n').filter(p => p.trim().length > 0);
  if (paragraphs.length > 0) {
    return paragraphs[paragraphs.length - 1];
  }
  
  // 方案3：自定义匹配规则
  const customMatch = rawResponse.match(/最终生成的回答是：(.+)/);
  if (customMatch) {
    return customMatch[1].trim();
  }
  
  // 保底方案：返回原始内容
  return rawResponse;
}

// 发送消息的函数
const sendMessage = async () => {
  // 如果输入为空或正在加载，则返回
  if (!inputMessage.value.trim() || loading.value) return
  
  // 添加用户消息到消息列表
  const userMessage = inputMessage.value.trim()
  messages.value.push({
    role: 'user',
    content: userMessage
  })
  
  // 清空输入框并设置加载状态
  inputMessage.value = ''
  loading.value = true
  scrollToBottom()
  
  try {
    // 调用API发送消息
    const response = await chatApi.chat(userMessage)
    
    // 处理API响应，提取最终回答
    const finalResponse = extractFinalResponse(response.data)
    
    // 添加AI回复到消息列表
    messages.value.push({
      role: 'assistant',
      content: finalResponse
    })
  } catch (error) {
    console.error('Chat error:', error)
    // 出错时添加错误消息
    messages.value.push({
      role: 'assistant',
      content: '抱歉，我遇到了些问题，无法回答您的问题。'
    })
  } finally {
    // 无论成功失败，都取消加载状态并滚动到底部
    loading.value = false
    scrollToBottom()
  }
}

// 清空聊天记录的函数
const clearChat = () => {
  messages.value = [
    {
      role: 'assistant',
      content: '您好！我是AI助手，有什么可以帮您的吗？'
    }
  ]
}

// 组件挂载时滚动到底部
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped lang="scss">
.chat-container {
  max-width: 800px;
  height: 90vh;
  margin: 20px auto;
  padding: 0 15px;
  display: flex;
  flex-direction: column;

  .chat-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    
    :deep(.el-card__header) {
      padding: 15px 20px;
      background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
      border-bottom: none;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-title {
          color: white;
          font-size: 18px;
          font-weight: 600;
        }
        
        .el-button {
          background-color: rgba(255, 255, 255, 0.2);
          border: none;
          color: white;
          
          &:hover {
            background-color: rgba(255, 255, 255, 0.3);
          }
        }
      }
    }
    
    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 0;
    }
  }
}

.chat-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0 20px;
}

.chat-messages {
  flex: 1;
  padding: 20px 0;
 
  /* 移除 overflow-y: auto */
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-track {
    background-color: transparent;
  }
}

.message {
  display: flex;
  margin-bottom: 24px;
  animation: fadeIn 0.3s ease;
  
  .message-avatar {
    flex-shrink: 0;
    margin-right: 15px;
    
    .el-avatar {
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .message-content {
    flex: 1;
    min-width: 0;
    
    .message-role {
      font-size: 13px;
      font-weight: 600;
      margin-bottom: 6px;
      color: #666;
    }
    
    .message-text {
      line-height: 1.6;
      padding: 12px 16px;
      border-radius: 12px;
      background-color: #f5f7fa;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
      word-break: break-word;
    }
  }
  
  &.user {
    flex-direction: row-reverse;
    
    .message-avatar {
      margin-right: 0;
      margin-left: 15px;
    }
    
    .message-content {
      text-align: right;
      
      .message-text {
        background-color: #e1f0ff;
        border-top-right-radius: 4px;
        color: #1a73e8;
      }
    }
  }
  
  &.assistant {
    .message-text {
      background-color: #f5f7fa;
      border-top-left-radius: 4px;
    }
    
    .is-loading {
      animation: rotating 2s linear infinite;
      margin-right: 8px;
    }
    
    .loading-text {
      color: #888;
    }
  }
}

.chat-input-area {
  padding: 16px 20px;
  border-top: 1px solid #eee;
  background-color: #fff;
  
  .input-box {
    :deep(.el-textarea__inner) {
      border-radius: 12px;
      padding: 12px 16px;
      box-shadow: none;
      border: 1px solid #e0e0e0;
      resize: none;
      
      &:focus {
        border-color: #2575fc;
      }
    }
  }
  
  .input-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
    
    .send-button {
      padding: 8px 20px;
      font-weight: 500;
      
      .icon-right {
        margin-left: 5px;
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>